/*
 * @Author: 瞿旺兴 18774621495@163.com
 * @Date: 2022-06-17 10:30:58
 * @LastEditors: 瞿旺兴 18774621495@163.com
 * @LastEditTime: 2022-06-20 11:16:44
 * @FilePath: \nien-vue3-admin\src\utils\viewCaches.ts
 * @Description: 标签页缓存操作
 */

import useRouters from '@/store/modules/router'
import useUserStore from "@/store/modules/user"

const storeName = "viewCatches"
let userId = ""

const getUserId = () => {
  const userStore = useUserStore()
  if(userId && userId !== userStore.user?.userId){
    //清除上个账号记录 
    clearViewStorage()
  }
  userId = userStore.user?.userId
}
//有权限的路由
let hasPermissionsRoutes = []
const getAllRoute = () => {
   if (hasPermissionsRoutes.length) return
   const router = useRouters()
   const fn = (arr) => {
      for (const p of arr) {
        hasPermissionsRoutes.push(p)
        if (p.children?.length) {
           fn(p.children)
        }
      }
   }
   fn(router.accessedRoutes)
}

//过滤权限路由
const routerFilter = () => {
  getUserId()
  let store = JSON.parse(sessionStorage[storeName] || "{}") 
  let views = store[userId] || []
  getAllRoute()
  return views.filter(item => hasPermissionsRoutes.some(p => p.name === item.name))
}



export const setViewStorage = (routes) => {
  getUserId()
  sessionStorage[storeName] = JSON.stringify({
    [userId]: routes.map(item => {
      const route = item
      //会报json循环引用错误
      delete route.matched
      return route
  })})
}
 
export const getViewStorage = () => {
  return routerFilter()
}

export const getCacheStorage = () => {
   const views = routerFilter()
   return views.filter(i => !i?.meta?.affix).map(i => i.name)
}

export const clearViewStorage = () => {
  hasPermissionsRoutes = []
  const userStore = useUserStore()
  // 账号未切换不清除
  if(userId === userStore.user?.userId) return
  sessionStorage[storeName] = ""
}


